<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Page</title>
    <style>
        /* 起手式, 100%保证我们的样式设置可以不受默认影响 */
        * {
            /* 消除网页的默认外边距 */
            margin: 0px;
            /* 消除网页的默认内边距 */
            padding: 0px;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
        }

        .container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        .container .navbar {
            width: 100%;
            height: 50px;
            background-color: black;
            /* 给父级标签设置overflow，取消后续float带来的影响 */
            overflow: hidden;
        }

        .container .navbar a {
            /* 设置a标签是行内块元素，允许你设置宽度 */
            display: inline-block;
            /* 设置a标签的宽度,a标签默认行内元素，无法设置宽度 */
            width: 80px;
            /* 设置字体颜色 */
            color: white;
            /* 设置字体的大小 */
            font-size: large;
            /* 设置文字的高度和导航栏一样的高度 */
            line-height: 50px;
            /* 去掉a标签的下划线 */
            text-decoration: none;
            /* 设置a标签中的文字居中 */
            text-align: center;
        }

        /* 设置鼠标事件 */
        .container .navbar a:hover {
            background-color: green;
        }

        .container .navbar .login {
            float: right;
        }

        .chat-area {
            display: flex;
            flex: 1;
            border-top: 1px solid #ccc;
            border-bottom: 1px solid #ccc;
            flex-direction: column;
            overflow-y: auto;
            padding: 10px;
        }

        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
            max-width: 80%;
        }

        .message.my-message {
            background-color: #d1ecf1;
            color: #0c5460;
            align-self: flex-end;
        }

        .message.other-message {
            background-color: #f8d7da;
            color: #721c24;
            align-self: flex-start;
        }

        .input-area {
            display: flex;
            align-items: center;
            padding: 10px;
            background-color: #f0f0f0;
        }

        .input-area input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }

        .input-area button {
            padding: 10px 20px;
            border: none;
            background-color: #333;
            color: #fff;
            border-radius: 5px;
            cursor: pointer;
        }

        .input-area button:hover {
            background-color: #555;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 导航 -->
        <div class="navbar">
            <a href="/">首页</a>
            <a href="/all_questions">题库</a>
            <a href="#">竞赛</a>
            <a href="/chat_page">讨论</a>
            <a href="#">求职</a>
            <a class="login" href="/loginhtml" id="login-link">{{usr}}</a>
        </div>
        <!-- 聊天栏 -->
        <div class="chat-area" id="chatArea">
        </div>
        <!-- 消息输入与发送 -->
        <div class="input-area">
            <input type="text" id="messageInput" placeholder="Type a message...">
            <button id="sendButton">Send</button>
        </div>
    </div>
    <!-- 引入jQuery库 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入jQuery Cookie插件 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#sendButton').click(function () {
                var message = $('#messageInput').val();
                if (message.trim() !== '') {
                    sendMessage(message);
                    $('#messageInput').val('');
                }
                else {
                    alert('请输入内容');
                }
            });

            $('#messageInput').keypress(function (event) {
                if (event.which === 13) {
                    $('#sendButton').click();
                }
            });

            function sendMessage(message) {
                var session = $.cookie('sessionId');

                $.ajax({
                    method: 'POST',
                    url: '/char_send', // 发送消息
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify({
                        'text': message,
                        'sessionId': session,
                    }),
                    success: function (data) {
                        if (data.success) {
                            var normalTime = convertTimestamp(data.nowtim);
                            addMessageToChat('my-message', data.idname, normalTime, data.chatText);
                        } else {
                            alert('请登录后发送');
                        }
                    }
                });
            }

            function addMessageToChat(className, idname, nowtim, chatText) {
                var messageElement = $('<div></div>').addClass('message ' + className);
                messageElement.html(`<strong>${idname}</strong> (${nowtim})<br>${chatText}`);
                $('#chatArea').append(messageElement);
                $('#chatArea').scrollTop($('#chatArea')[0].scrollHeight);
            }

            // 系统提示需要登录使用
            function simulateServerMessages() {
                var usr = $('#login-link').text();
                setTimeout(function () {
                    if (!$.cookie('sessionId')) {
                        addMessageToChat('other-message', '系统', 'null', '您没有登录无法使用哦');
                    }
                    else {
                        addMessageToChat('other-message', '系统', 'null', usr + '欢迎使用');
                    }
                }, 1);
            }

            // 定时接收消息
            setInterval(function () {
                var session = $.cookie('sessionId');
                if (!$.cookie('sessionId')) {
                    return;
                }
                $.ajax({
                    method: 'POST',
                    url: '/char_recv',// 接受消息
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify({
                        sessionId: session
                    }),
                    success: function (data) {
                        if (data.success) {
                            var normalTime = convertTimestamp(data.nowtim);
                            addMessageToChat('other-message', data.idname, normalTime, data.chatText);
                        }
                    }
                });
            }, 150);



            simulateServerMessages();
        });
        //时间戳转换为时分秒
        function convertTimestamp(timestamp) {
            var date = new Date(timestamp * 1000);
            return date.toLocaleString();
        }
        //消除指定cookie值
        function clearCookie(name) {
            document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        }
        $('#login-link').click(function (event) {
            if ($.cookie('sessionId')) {
                event.preventDefault();
                clearCookie("sessionId");
                alert('你退出登录了');
                window.location.href = window.location.href;
            }
        });

    </script>
</body>

</html>